import {
  fetchHome
} from "../../services/home/home";
import {
  fetchGoodsList
} from "../../services/good/fetchGoods";
import Toast from "tdesign-miniprogram/toast/index";

import {
  queryArticleAll
} from "../../services/article/article";
import {
  login_code
} from "../../services/login/login";
import Message from 'tdesign-miniprogram/message/index';

var app=getApp()
Page({
  data: {
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    articleList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 0,
    autoplay: true,
    duration: "500",
    interval: 5000,
    navigation: {
      type: "dots",
    },
    swiperImageProps: {
      mode: "scaleToFill",
    },
    goodsListLoadStatus: 0,
    total: 0,
    currentPages: 1,
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {
    this.getTabBar().init();
  },

  loginIn() {
    var that = this
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          console.log(res);
          login_code({
            code:res.code
          }).then(res=>{
            if (res.data.code === 200) {
              const token="Bearer "+res.data.data.token;
              wx.setStorageSync('token',token )
              console.log("用户登录token");
              console.log(token);
              app.globalData.token=token;
              app.globalData.uid=res.data.data.uid;
              console.log("全局变量token");
              console.log(app.globalData.token);
              // 如果是新用户，通知时间长一点
              if (res.data.data.isNewUser===true) {
                Message.info({
                  context: this,
                  offset: ['20rpx', '32rpx'],
                  duration: 5000,
                  content: '新用户：'+res.data.data.username+" 新用户密码默认：123",
                });
              }else{
                Message.info({
                  context: this,
                  offset: ['20rpx', '32rpx'],
                  duration: 2000,
                  content: "登录成功"
                });
              }
            }else{
              Message.info({
                context: this,
                offset: ['20rpx', '32rpx'],
                duration: 2000,
                content: "登录失败"
              });
            }
          })
      
        }
      }
    })
  },
  onLoad() {
    // this.loginIn();
    this.init();
  },

  onReachBottom() {
    console.log("触发了事件onReachBottom");
    console.log(this.data.currentPages + 1);
    console.log(this.data.total);
    if ((this.data.currentPages + 1) > this.data.total) {
      Toast({
        context: this,
        selector: "#t-toast",
        message: "对不起，一共" + this.data.total + "页，已经到达底部",
      });
      return;
    }
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    console.log("触发了顶部刷新的操作");
    this.init();
  },

  init() {
    this.loadHomePage();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });

    const swiper = [
      "https://fakerlove.oss-cn-beijing.aliyuncs.com/kaoyan/2024/03/15/2492c5781c714e118d0140e152c2530a1.png",
      "https://fakerlove.oss-cn-beijing.aliyuncs.com/kaoyan/2024/03/25/4a64bd881acf48dfa4267ef04b00f4881.jpeg",
    ];
    const tabList = [{
        text: "今日短文",
        key: 0,
      },
      {
        text: "经典小说",
        key: 1,
      },
    ];
    this.setData({
      tabList,
      imgSrcs: swiper,
      pageLoading: false,
      articleList: [],
      total: 1
    });
    this.getData(1);
  },

  async getData(current) {
    const res = await queryArticleAll({
      pageSize: 6,
      pageNum: current,
      type: 1
    }).then((res) => {
      this.setData({
        currentPages: res.data.data.current,
        articleList: [...this.data.articleList, ...res.data.data.records],
        total: res.data.data.pages
      });
      return res.data.data.records;
    }).catch(error => {
      Toast({
        context: this,
        selector: "#t-toast",
        message: error,
      });
      return [];
    });
    // return res.data.data.records;
    console.log(res);
    return res;
  },
  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    this.loadGoodsList(true);
  },

  // 
  onReTry() {
    console.log("点击了onReTry");
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    this.setData({
      goodsListLoadStatus: 1,
    });
    // 这里正在加载数据
    const data = await this.getData(this.data.currentPages + 1);
    this.setData({
      goodsListLoadStatus: 0,
    });
    // console.log(this.data.imgSrcs);
    // console.log(this.data.articleList);
  },
  // 跳转到详情页
  goodListClickHandle(e) {
    const data = e.currentTarget.dataset.index
    const spuId = data.id;
    wx.navigateTo({
      url: `/pages/article/details/index?spuId=${spuId}`,
    });
  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: "#t-toast",
      message: "点击加入购物车",
    });
  },

  // 跳转到搜索页
  navToSearchPage() {
    wx.navigateTo({
      url: "/pages/article/search/index",
    });
  },

  navToActivityDetail({
    detail
  }) {
    const {
      index: promotionID = 0
    } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },
});